package service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import domain.CreditCard;
import domain.Person;

@Service("creditCardService")
@Transactional
public class CreditCardService {
	protected static Logger log = Logger.getLogger(CreditCardService.class);

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	public List<CreditCard> getAll(int personId) {
		log.info("Retriving get all credit card of person id : " + personId);
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM Person as p LEFT JOIN FETCH p.creditCards where p.id=:id");
		query.setParameter("id", personId);
		return query.list();
	}

	public void addCreditCard(int personId, CreditCard creditCard) {
		log.info("Retriving add a creditcard into person id : " + personId);
		Session session = sessionFactory.getCurrentSession();
		Person exitsPerson = (Person) session.get(Person.class, personId);
		if (null != exitsPerson) {
			exitsPerson.getCreditCards().add(creditCard);
			session.save(exitsPerson);
		}
	}

	public void editCreditCard(CreditCard creditCard) {
		log.info("Retriving edit creditcard : " + creditCard.getId());
		Session session = sessionFactory.getCurrentSession();
		CreditCard existCreditCard = (CreditCard) session.get(CreditCard.class, creditCard.getId());
		existCreditCard.setCreditCardNumber(creditCard.getCreditCardNumber());
		existCreditCard.setType(creditCard.getType());
		session.save(existCreditCard);
	}

	public void deleteCreditCard(int creditCardId) {
		log.info("Retriving delete credit card : " + creditCardId);
		Session session = sessionFactory.getCurrentSession();
		// delete credit card in person_credit_card table
		Query query = session.createQuery("DELETE from person_credit_card where creditCards_id =:id");
		query.setParameter("id", creditCardId);
		query.executeUpdate();

		// delete credit card
		CreditCard creditCard = (CreditCard) session.get(CreditCard.class, creditCardId);
		session.delete(creditCard);
	}

}
